package cloud.banson.emojilizer.home

import android.content.Context
import android.net.Uri
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import cloud.banson.emojilizer.network.BASE_URL
import cloud.banson.emojilizer.repo.EmojilizerRepo
import cloud.banson.emojilizer.utils.TAG
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

/**
 * This is the model that will be used to represent the user's home screen.
 * The code then declares two variables: context and resultImgUri.
 * These are both mutable state variables, meaning they can change over time as needed.
 */
class HomeViewModel : ViewModel() {
    lateinit var context: Context

    var originImgUri by mutableStateOf<Uri?>(null)

    var resultImgUri by mutableStateOf<Uri?>(null)

    /**
     * creates an instance of EmojilizerRepo using the context variable from before,
     * which is declared in this same file as a lazy property named repository.
     */
    private val repository by lazy { EmojilizerRepo(context = context) }

    fun invalidateResultUrl() {
        resultImgUri = null
    }

    fun fetchResponse(hintUser: (String) -> Unit) {
        Log.d(TAG, "fetchResponse: invoked")
        originImgUri?.let { uri: Uri ->
            CoroutineScope(Job() + Dispatchers.IO).launch {
                resultImgUri = Uri.parse(BASE_URL + repository.uploadImgForResult(uri, hintUser))
            }
        }
    }

    fun fakeFetchResponse() {
        resultImgUri =
            Uri.parse("https://images.unsplash.com/photo-1633113214186-9f1e186498fe")
        Log.d(TAG, "fakeFetchResponse: $resultImgUri")
    }
}